import numpy as na
import Image
import scipy.ndimage as ndi

def win_lev(a, w, l):
    """Window (w) and level (l) data in a"""
    maxc = 255
    m = maxc/(2.0*w)
    o = m*(l-w)
    return na.clip((m*a-o),0,maxc).astype(na.uint8)
def ArrayToPilImageStraight(a, debug=True):
    try:
        i = Image.new("L",(a.shape[1],a.shape[0]))
        if( debug ): print "created image"
        i.fromstring(a.tostring())
        if( debug ): print "converted image to string"
        return i
    except Exception, error:
        print "failed in MyIU.ArrayToPilImageStraight", error
        return []
def ArrayToPilImageBland(a):
	i = Image.new("L",(a.shape[1],a.shape[0]))
	i.fromstring(win_lev(a,255,127).tostring())
	return i

def ArrayToPilImage(a, scale=1,win=None, lev=None):
    """Create Pil Image from na array"""
    max_a = max(a.flat)
    print "Maximum of input image",max(a.flat)
    if( win == None):
	win = max_a/6
    if( lev == None):
	lev = 0.25*max_a
    a = win_lev(a,win,lev)
    print "Shape of win_lev image",a.shape
    print "Maximum value of win_lev image",max(a.flat)
    i = Image.new("L", (a.shape[1], a.shape[0]), color=255)
    i.fromstring(a.tostring())
    if scale != 1:
        i = i.resize((i.size[0]*scale, i.size[1]*scale))
    return i

def PilImageToArray(i):
    """Takes an L-mode PIL image and returns a numpy int8 array"""
    try:    
        a = na.fromstring(i.tostring(), na.int8)
        a = na.reshape(a,(i.size[1], i.size[0]))
        return a
    except Exception, error:
        print "failed in PilImageToArray", error

def monoarraytoRGB(a):
    """a: numeric array

    takes a 2D numeric array and replicates it to a (NxNx3)
    string for creation of an RGB image
    Image is flipped up down to match display 
    """
    a_rgb = na.transpose(na.array((a,a,a)).astype(na.uint8),(2,1,0)).tostring()
    return a_rgb


def get_crds(inds,dim):
        """Assuming dim is the numarray shape [z,y,x]"""
	try:
	    inds = na.array(inds)
	    crd = [ inds % dim[2], (inds/dim[2])%dim[1], inds/(dim[1]*dim[2])]
	    return crd
	except Exception, error:
	    print "failed in get_crds ", error
	    return -1
def getLargestLabeledRegion(img):
    """using the numarray.nd_image.label data return the largest segmented
       region"""
    try:
        labeled, numlabels = ndi.label(img)
        
        ml = -1
        mc = -1
        for l in xrange(1,numlabels+1):
            count = len(na.nonzero(labeled == l)[0])
            if( count > mc ):
                mc = count
                ml = l
        return na.where(labeled == ml)[0]
    except Exception, error:
        print "failed in getLargestLabeledRegion()", error
        return None
    
